package com.labi.designpattern.service;


import com.labi.designpattern.database.MockDB;
import com.labi.designpattern.entity.OrderEntity;
import com.labi.designpattern.enums.OrderEvent;
import com.labi.designpattern.enums.OrderState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.statemachine.state.State;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service

public class OrderService {

    @Autowired
    private  StateMachine<OrderState, OrderEvent> orderStateMachine;
    @Autowired
    private StateMachinePersister<OrderState, OrderEvent, String> persister;



    @Autowired
    public OrderService(StateMachine<OrderState, OrderEvent> orderStateMachine) {
        System.out.println("OrderService 初始化构造");

        this.orderStateMachine = orderStateMachine;
    }

    public String createOrder() {
        // 假设订单已经创建，现在触发状态机到CREATED状态
        // 实际上，这里可能涉及订单的创建逻辑
//        System.out.println("Order created and state machine started in state: " + orderStateMachine.getState().getId());
        String orderIdNew = String.valueOf(System.currentTimeMillis());
        System.out.println("创建订单成功,这里要返回订单号 "+orderIdNew);
        Message<OrderEvent> orderEventMessage = MessageBuilder.withPayload(OrderEvent.ORDER_INIT)
                .setHeader("headerName1", "headerValue1")
                .setHeader("orderId",orderIdNew)
                .build();
        this.sendEvent(orderEventMessage, orderIdNew);

        return orderIdNew;

    }
    public void checkOrder(String orderid) {
        // 发送支付事件，状态机将转移到PAID状态
//        orderStateMachine.sendEvent(OrderEvent.CHECK_EVENT); //这样不带参数的  使用场景不多
        //---
        Message<OrderEvent> orderEventMessage = MessageBuilder.withPayload(OrderEvent.CHECK_EVENT)
                .setHeader("headerName1", "headerValue1")
//                .setHeader("orderId","orderid00001")
                .setHeader("orderId",orderid)
                .build();
//        orderStateMachine.sendEvent(orderEventMessage); //实际业务场景 需要带参数
//        this.sendEvent(orderEventMessage, "test");
        this.sendEvent(orderEventMessage, orderid);
        System.out.println("订单号:"+orderid+"  "+"Order paid and state machine is now in state: " + orderStateMachine.getState().getId());

    }
    public void payOrder(String orderId) {
        // 发送支付事件，状态机将转移到PAID状态
        Message<OrderEvent> orderEventMessage = MessageBuilder.withPayload(OrderEvent.PAY_EVENT)
                .setHeader("headerName1", "headerValue1")
//                .setHeader("orderId","orderid00001")
                .setHeader("orderId",orderId)
                .build();
        this.sendEvent(orderEventMessage, orderId);
        System.out.println("订单号:"+orderId+"  "+"Order paid and state machine is now in state: " + orderStateMachine.getState().getId());
    }




    public void completeOrder(String orderId) {
        // 发送完成事件，状态机将转移到COMPLETED状态
        Message<OrderEvent> orderEventMessage = MessageBuilder.withPayload(OrderEvent.WRITEBACK_EVENT)
                .setHeader("headerName1", "headerValue1")
//                .setHeader("orderId","orderid00001")
                .setHeader("orderId",orderId)
                .build();
        this.sendEvent(orderEventMessage, orderId);
//        orderStateMachine.sendEvent(OrderEvent.WRITEBACK_EVENT);
        System.out.println("订单号:"+orderId+"  "+"Order completed and state machine is now in state: " + orderStateMachine.getState().getId());
    }

    public Map<String, OrderState> getOrders() {
        return MockDB.orders;
    }


//    private synchronized boolean sendEvent(Message<OrderEvent> message, String orderId) {
     private synchronized boolean sendEvent(Message<OrderEvent> message, String orderId) {
        boolean result = false;
        try {
            orderStateMachine.start();
            //尝试恢复状态机状态

            persister.restore(orderStateMachine,orderId );
            //添加延迟用于线程安全测试
            Thread.sleep(1000);
            result = orderStateMachine.sendEvent(message);
            //持久化状态机状态
            persister.persist(orderStateMachine, orderId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("执行了 orderStateMachine.stop();");
            orderStateMachine.stop();
        }
        return result;
    }
}